﻿$(function () {
    window.progressDialog = new ProgressDialog();
    window.infoDialog = new InfoDialog();
    window.ajaxClass = new AjaxClass();

    $("#List1").flexigrid({
        colModel: [
                { display: '自动编号', name: 'AutoID', width: 50, sortable: false, align: 'left' },
                { display: '一级菜单名称', name: 'Name', width: 150, sortable: false, align: 'left' }
                ],

        buttons: [
                { name: '添加', bclass: 'List1 add', onpress: FlexiGrid_AddRecord },
                { name: '修改', bclass: 'List1 edit', onpress: FlexiGrid_EditRecord },
                { name: '删除', bclass: 'List1 delete', onpress: FlexiGrid_DeleteRecord },
                { name: '保存排序', bclass: 'List1 save', onpress: FlexiGrid_SortRecord }
                ],

        dataType: 'json',
        width: "auto",
        height: "auto",
        resizable: false,
        showToggleBtn: false,
        striped: true,

        nonSelect: false,
        singleSelect: true,

        procmsg: '正在处理数据，请稍候……',
        nomsg: '没有符合条件的记录存在。',
        errormsg: '处理数据时出错，请与系统管理员联系！',

        onError: FlexiGrid_Error,
        onRowClick: FlexiGrid_RowClick
    });
    $(".flexigrid .hDiv").bind("selectstart", function () { return false; });

    $("#List2").flexigrid({
        colModel: [
                { display: '自动编号', name: 'AutoID', width: 50, sortable: false, align: 'left' },
                { display: '二级菜单名称', name: 'Name', width: 150, sortable: false, align: 'left' }
                ],

        buttons: [
                { name: '添加', bclass: 'List2 add', onpress: FlexiGrid_AddRecord },
                { name: '修改', bclass: 'List2 edit', onpress: FlexiGrid_EditRecord },
                { name: '删除', bclass: 'List2 delete', onpress: FlexiGrid_DeleteRecord },
                { name: '保存排序', bclass: 'List2 save', onpress: FlexiGrid_SortRecord }
                ],

        dataType: 'json',
        width: "auto",
        height: "auto",
        resizable: false,
        showToggleBtn: false,
        striped: true,

        nonSelect: false,
        singleSelect: true,

        procmsg: '正在处理数据，请稍候……',
        nomsg: '没有符合条件的记录存在。',
        errormsg: '处理数据时出错，请与系统管理员联系！',

        onError: FlexiGrid_Error,
        onRowClick: FlexiGrid_RowClick
    });
    $(".flexigrid .hDiv").bind("selectstart", function () { return false; });

    $("#List3").flexigrid({
        colModel: [
                { display: '自动编号', name: 'AutoID', width: 50, sortable: false, align: 'left' },
                { display: '三级菜单名称', name: 'Name', width: 150, sortable: false, align: 'left' }
                ],

        buttons: [
                { name: '添加', bclass: 'List3 add', onpress: FlexiGrid_AddRecord },
                { name: '修改', bclass: 'List3 edit', onpress: FlexiGrid_EditRecord },
                { name: '删除', bclass: 'List3 delete', onpress: FlexiGrid_DeleteRecord },
                { name: '保存排序', bclass: 'List3 save', onpress: FlexiGrid_SortRecord }
                ],

        dataType: 'json',
        width: "auto",
        height: "auto",
        resizable: false,
        showToggleBtn: false,
        striped: true,

        nonSelect: false,
        singleSelect: true,

        procmsg: '正在处理数据，请稍候……',
        nomsg: '没有符合条件的记录存在。',
        errormsg: '处理数据时出错，请与系统管理员联系！',

        onError: FlexiGrid_Error,
        onRowClick: FlexiGrid_RowClick
    });
    $(".flexigrid .hDiv").bind("selectstart", function () { return false; });

    $("#EditerDialog").dialog({
        autoOpen: false,
        resizable: false,
        height: 256,
        width: 521,
        modal: true,
        zIndex: 1000,
        buttons: {
            提交: function () {
                if ($("#EditerTable").find("input[name='Name']").val() != "") {
                    var TempJson = [[{ "OperationKey": "检查重复", "Parameters": { "@ParentID": $("#EditerTable").find("input[name='ParentID']").val() == "" ? 0 : $("#EditerTable").find("input[name='ParentID']").val(), "@Name": $("#EditerTable").find("input[name='Name']").val(), "@AutoID": $("#EditerTable").find("input[name='AutoID']").val()}}]];
                    var ActionOperation = { "OperationKey": null, "Parameters": null };
                    if ($("#EditerTable").find("input[name='AutoID']").val() == "-1") {
                        ActionOperation.OperationKey = "添加菜单";
                    } else {
                        ActionOperation.OperationKey = "修改菜单";
                    }
                    ActionOperation.Parameters = { "@ParentID": $("#EditerTable").find("input[name='ParentID']").val() == "" ? null : $("#EditerTable").find("input[name='ParentID']").val(), "@Name": $("#EditerTable").find("input[name='Name']").val(), "@Icon": $("#EditerTable").find("input[name='Icon']").val(), "@URL": $("#EditerTable").find("input[name='URL']").val(), "@Permissions": $("#EditerTable").find("input[name='Permissions']").val(), "@ListOrder": $("#EditerTable").find("input[name='ListOrder']").val(), "@AutoID": $("#EditerTable").find("input[name='AutoID']").val() };
                    TempJson.push([ActionOperation]);
                    TempJson.push([{ "OperationKey": "菜单列表", "Parameters": null}]);
                    var JsonSend = { "ActionParameters": JSON.stringify(TempJson) };
                    window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "JsonOriginal.Operations[\"菜单列表\"].OperationData = data.ReturnData[2];ResetList(window.CurrentListID);$(\"#EditerDialog\").dialog(\"close\");", "", true, true);
                } else {
                    infoDialog.OpenDialog("菜单名称必须填写！", "Alert");
                }
            },
            取消: function () {
                $(this).dialog("close");
            }
        }
    });
});

/* 列表事件 --------------------------------------------------------------------------------------------*/

function FlexiGrid_Error(XMLHttpRequest, textStatus, errorThrown) {
    infoDialog.OpenDialog("处理数据时出错，请与系统管理员联系！", "Error");
}

function FlexiGrid_RowClick(Obj, g, p) {
    switch ($(Obj).parent().parent().attr("id")) {
        case "List1":
            GetListData(parseInt(-1), "List3");
            if ($("#List1 .trSelected").size() > 0) {
                GetListData(parseInt($("#List1 .trSelected").find("div:first").html()), "List2");
            } else {
                GetListData(parseInt(-1), "List2");
            }
            break;
        case "List2":
            if ($("#List2 .trSelected").size() > 0) {
                GetListData(parseInt($("#List2 .trSelected").find("div:first").html()), "List3");
            } else {
                GetListData(parseInt(-1), "List3");
            }
            break;
    }
    SetButton(true);
}

function FlexiGrid_EditRecord(Obj, g, p) {
    DialogOpen(this, "修改");
    if ($(this).find(".List1").size() > 0) {
        FillEditerTable(parseInt($("#List1 .trSelected").find("div:first").html()));
    } else if ($(this).find(".List2").size() > 0) {
        FillEditerTable(parseInt($("#List2 .trSelected").find("div:first").html()));
    } else if ($(this).find(".List3").size() > 0) {
        FillEditerTable(parseInt($("#List3 .trSelected").find("div:first").html()));
    }
}

function FlexiGrid_AddRecord(Obj, g, p) {
    DialogOpen(this, "添加");
    if ($(this).find(".List1").size() > 0) {
        $("#EditerTable").find("input[name='ParentID']").val("");
    } else if ($(this).find(".List2").size() > 0) {
        $("#EditerTable").find("input[name='ParentID']").val($("#List1 .trSelected").find("div:first").html());
    } else if ($(this).find(".List3").size() > 0) {
        $("#EditerTable").find("input[name='ParentID']").val($("#List2 .trSelected").find("div:first").html());
    }
}

function FlexiGrid_DeleteRecord(Obj, g, p) {
    var DeleteInfo = "";
    window.CurrentListID = null;
    if ($(this).find(".List1").size() > 0) {
        DeleteInfo = "选中的一级菜单以及其子菜单将会被永久删除？";
        window.CurrentListID = "List1";
    } else if ($(this).find(".List2").size() > 0) {
        DeleteInfo = "选中的二级菜单以及其子菜单将会被永久删除？";
        window.CurrentListID = "List2";
    } else if ($(this).find(".List3").size() > 0) {
        DeleteInfo = "选中的三级菜单将会被永久删除？";
        window.CurrentListID = "List3";
    }
    infoDialog.OpenDialog(DeleteInfo, "Alert", function () {
        if (window.CurrentListID != null) {
            var JsonSend = { "ActionParameters": JSON.stringify([[{ "OperationKey": "删除菜单", "Parameters": { "@AutoID": parseInt($("#" + window.CurrentListID + " .trSelected").find("div:first").html())}}], [{ "OperationKey": "菜单列表", "Parameters": null}]]) };
            window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "JsonOriginal.Operations[\"菜单列表\"].OperationData = data.ReturnData[1];$('#' +  window.CurrentListID + ' .trSelected').remove();ResetList(window.CurrentListID);", "", true, true);
        }
    });
}

function FlexiGrid_SortRecord(Obj, g, p) {
    var ObjID;
    if ($(this).find(".List1").size() > 0) {
        ObjID = "#List1";
    } else if ($(this).find(".List2").size() > 0) {
        ObjID = "#List2";
    } else if ($(this).find(".List3").size() > 0) {
        ObjID = "#List3";
    }

    var TempJson = new Array();
    var ActionOperations = new Array();
    var AutoID;
    $(ObjID + " tbody tr").each(function (index, element) {
        AutoID = parseInt($(element).find("div:first").html());
        ActionOperations.push({ "OperationKey": "排序菜单", "Parameters": { "@AutoID": AutoID, "@ListOrder": index + 1} });
    });
    TempJson.push(ActionOperations);
    TempJson.push([{ "OperationKey": "菜单列表", "Parameters": null}]); 
    var JsonSend = { "ActionParameters": JSON.stringify(TempJson) };
    window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "JsonOriginal.Operations[\"菜单列表\"].OperationData = data.ReturnData[1];", "", true, true);
}

/* 功能方法 --------------------------------------------------------------------------------------------*/

function DialogOpen(evenObj, Preamble) {
    if ($(evenObj).find(".List1").size() > 0) {
        $("#EditerDialog").parent().find(".ui-dialog-title").html(Preamble + "一级菜单");
        $("#EditerTable").find("input[name='Icon']").removeAttr("readonly");
        $("#EditerTable").find("input[name='URL']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='Permissions']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='URL']").val("");
        window.CurrentListID = "List1";
    }
    if ($(evenObj).find(".List2").size() > 0) {
        $("#EditerDialog").parent().find(".ui-dialog-title").html(Preamble + "二级菜单");
        $("#EditerTable").find("input[name='Icon']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='URL']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='Permissions']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='URL']").val("");
        window.CurrentListID = "List2";
    }
    if ($(evenObj).find(".List3").size() > 0) {
        $("#EditerDialog").parent().find(".ui-dialog-title").html(Preamble + "三级菜单");
        $("#EditerTable").find("input[name='Icon']").attr("readonly", "readonly");
        $("#EditerTable").find("input[name='URL']").removeAttr("readonly");
        $("#EditerTable").find("input[name='Permissions']").removeAttr("readonly");
        $("#EditerTable").find("input[name='URL']").val("/Frame/coming/");
        window.CurrentListID = "List3";
    }
    $("#EditerTable").find("input[name='AutoID']").val("-1");
    $("#EditerTable").find("input[name='Name']").val("");
    $("#EditerTable").find("input[name='ParentID']").val("");
    $("#EditerTable").find("input[name='Icon']").val("");
    $("#EditerTable").find("input[name='Permissions']").val("");
    $("#EditerTable").find("input[name='ListOrder']").val("9999");
    $("#EditerDialog").dialog("open");
}       

function FillEditerTable(AutoID) {
    var i = 0;
    var ListObj = JsonOriginal.Operations["菜单列表"].OperationData;
    for (; i < ListObj.length; i++) {
        if (ListObj[i]["AutoID"] == AutoID) {
            break;
        }
    }
    $("#EditerTable").find("input[name='AutoID']").val(ListObj[i]["AutoID"]);
    $("#EditerTable").find("input[name='Name']").val(ListObj[i]["Name"]);
    $("#EditerTable").find("input[name='ParentID']").val(ListObj[i]["ParentID"]);
    $("#EditerTable").find("input[name='Icon']").val(ListObj[i]["Icon"]);
    $("#EditerTable").find("input[name='URL']").val(ListObj[i]["URL"]);
    $("#EditerTable").find("input[name='Permissions']").val(ListObj[i]["Permissions"]);
    $("#EditerTable").find("input[name='ListOrder']").val(ListObj[i]["ListOrder"]);
}

function ResetList(ListID) {
    switch (ListID) {
        case "List1":
            GetListData(parseInt(-1), "List3");
            GetListData(parseInt(-1), "List2");
            GetListData(null, "List1");
            break;
        case "List2":
            GetListData(parseInt(-1), "List3");
            GetListData(parseInt($("#List1 .trSelected").find("div:first").html()), "List2");
            break;
        case "List3":
            GetListData(parseInt($("#List2 .trSelected").find("div:first").html()), "List3");
            break;
    }
    SetButton(true);
}

function GetListData(ParentID, ListID) {
    var List_Data = { "page": 1, "total": 4, "rows": new Array() };
    if (ParentID > - 1) {
        var ListObj = JsonOriginal.Operations["菜单列表"].OperationData;
        for (var i = 0; i < ListObj.length; i++) {
            if (ListObj[i]["ParentID"] == ParentID && ListObj[i]["AutoID"] != -1) {
                List_Data.rows.push({ "cell": [ListObj[i]["AutoID"], ListObj[i]["Name"]] });
            }
        }
    }
    $("#" + ListID).flexAddData(List_Data);
    $("#" + ListID + " tr td div").each(function (index, element) { if ($(element).find("*").size() == 0) { $(element).attr("title", $(element).html() == "&nbsp;" ? "" : $(element).text()) } });
    SetListOrder("#" + ListID + " tbody");
    SetFlexiGridHeight(ListID);
}

function SetListOrder(Selector) {
    $(Selector).sortable();
    $(Selector).disableSelection();
}

function SetFlexiGridHeight(PanelID) {
    $("#" + PanelID).removeClass("autoht");
    $("#" + PanelID).parent().css("height", "auto");
    $("#" + PanelID).parent().css("height", ($("#" + PanelID).parent().innerHeight() + 27) + "px");
}

function SetButton(Fade) {
    SetShowHide(".List1.save", $("#List1 tr").size() > 0, Fade);
    SetShowHide(".List2.save", $("#List2 tr").size() > 0, Fade);
    SetShowHide(".List3.save", $("#List3 tr").size() > 0, Fade);

    SetShowHide(".List1.edit, .List1.delete, .List2.add", $("#List1 .trSelected").size() > 0, Fade);
    SetShowHide(".List2.edit, .List2.delete, .List3.add", $("#List2 .trSelected").size() > 0, Fade);
    SetShowHide(".List3.edit, .List3.delete", $("#List3 .trSelected").size() > 0, Fade);  
}

function SetShowHide(Selector, Show, Fade) {
    if (Show) {  
        if (Fade) {
            $(Selector).parent().parent().fadeIn("fast");
        } else {
            $(Selector).parent().parent().show();
        }
    } else {
        if (Fade) {
            $(Selector).parent().parent().fadeOut("fast");
        } else {
            $(Selector).parent().parent().hide();
        }
    }
}

/* 初始化 --------------------------------------------------------------------------------------------*/

$(function () {
    GetListData(null, "List1");
    SetFlexiGridHeight("List2");
    SetFlexiGridHeight("List3");
    SetButton(false);
});